
package isv

import (
    "dhfshop/models"
	"strings"
	"errors"
	"strconv"
	"time"
	"wxsdk/oauth"
	"github.com/astaxie/beego/orm"
)

type CustAccount struct {
	CustAccountId int64    `orm:"column(cust_account_id);pk;auto" json:"cust_account_id"`   //自增主键
    PartnerId     int64      `orm:"column(partner_id);index" json:"partner_id"`      // 分销商ID
	StoreId       int64      `orm:"column(store_id);index" json:"store_id"`         // 门店ID
	NickName      string   `orm:"column(nick_name)" json:"nick_name"`             //公众号微信昵称
	AppId         string   `orm:"column(app_id);size(32);unique" json:"app_id"`            //公众号appid
	AvartarUrl    string   `orm:"column(avartar_url)" json:"avartar_url"`         //公众号微信头像链接
	ServiceTypeId int    `orm:"column(service_type_id)" json:"service_type_id"` //公众号类型，1公众号，2小程序   
	VerifyTypeId  int    `orm:"column(verify_type_id)" json:"verify_type_id"`   //认证类型，-1代表未认证，0代表微信认证，1代表新浪微博认证
	PrincipalName string    `orm:"column(principal_name)" json:"principal_name"`   //公众号的主体名称
	Alias         string    `orm:"column(alias)" json:"alias"`                     //公众号所设置的微信号，可能为空
	OpenStore     int     `orm:"column(open_store)" json:"open_store"`           //是否开通微信门店功能: 1: 未开通；2：已开通 
	OpenScan      int     `orm:"column(open_scan)" json:"open_scan"`             //是否开通微信扫商品功能: 1: 未开通；2：已开通
    OpenPay       int     `orm:"column(open_pay)" json:"open_pay"`               //是否开通微信支付功能: 1: 未开通；2：已开通
	OpenCard      int     `orm:"column(open_card)" json:"open_card"`             //是否开通微信卡券功能: 1: 未开通；2：已开通
    OpenShake     int     `orm:"column(open_shake)" json:"open_shake"`           //是否开通微信摇一摇功能: 1: 未开通；2：已开通
	QrcodeUrl     string    `orm:"column(qrcode_url)" json:"qrcode_url"`           //二维码图片的URL
	FuncIds       string    `orm:"column(func_ids)" json:"func_ids"`            //公众号开放给第三方平台的权限列表ID
	Status        int16     `orm:"column(status)" json:"status"`                //-2: 逻辑删除；1：有效  
	AccessToken   string    `orm:"column(access_token)" json:"-"`               //
	ExpiresIn     int64     `orm:"column(expires_in)" json:"expires_in"`        //
	RefreshToken  string    `orm:"column(refresh_token)" json:"-"`              //刷新token
	TemplateId    int64     `orm:"column(template_id)" json:"template_id"`
	CreatedAt     time.Time `orm:"auto_now_add;column(created_at);type(datetime)" json:"-"`   
	UpdatedAt     time.Time `orm:"auto_now;column(updated_at);type(datetime)" json:"-"` 
	//PayParams  []*AcPayParams `orm:"reverse(many)" json:"pay_params,omitempty" form:"-"`       /* 反向关系*/
	Secret        string     `orm:"column(secret);size(40)" json:"secret"`        //小程序的秘钥
	//非数据库字段
	CreatedAtStr  string    `orm:"-" json:"created_at" form:"-"`
	UpdatedAtStr  string    `orm:"-" json:"updated_at" form:"-"`	
}

func init() {
    orm.RegisterModel(new(CustAccount))   
}

func AddCustAccount(m *CustAccount) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func GetCustAccountById(id int64) (v *CustAccount, err error) {
	o := models.GetDefaultDB()
	v = &CustAccount{CustAccountId: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetCustAccountByAppId(appId string) (v *CustAccount, err error) {
	o := models.GetDefaultDB()
	v = &CustAccount{AppId: appId}
	if err = o.Read(v, "AppId"); err == nil {
		return v, nil
	}
	return nil, err
}
/* 
因为查询信息不唯一，废弃
func GetCustAccountByStoreId(storeId int64) (v *CustAccount, err error) {
	o := models.GetDefaultDB()
	v = &CustAccount{StoreId: storeId}
	if err = o.Read(v, "StoreId"); err == nil {
		return v, nil
	}
	return nil, err
}
func GetCustAccountByPartnerId(partnerId int64) (v *CustAccount, err error) {
	o := models.GetDefaultDB()
	v = &CustAccount{PartnerId: partnerId}
	if err = o.Read(v, "PartnerId"); err == nil {
		return v, nil
	}
	return nil, err
}
*/
func QueryCustAccountsByPartnerId(partnerId int64, offset, limit int) (accounts []*CustAccount, err error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(CustAccount))
	qs = qs.Filter("partner_id", partnerId)
	var lists []*CustAccount
	if _, err := qs.Limit(limit, offset).All(&lists); err == nil {
		return lists, nil
	}
	return nil, err	
}

func QueryCustAccountsByStoreId(storeId int64) (accounts []*CustAccount, err error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(CustAccount))
	qs = qs.Filter("store_id", storeId)
	var lists []*CustAccount
	if _, err := qs.All(&lists); err == nil {
		return lists, nil
	}
	return nil, err	
}


func GetAllCustAccounts(storeIds []int64,query map[string]string, fields []string, order_by map[string]string, 
    offset int, limit int) ([]*CustAccount, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(CustAccount))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	if len(storeIds) > 0 {
        qs = qs.Filter("store_id__in", storeIds)
    }
	cnt, err := qs.Count()
	// order by:
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*CustAccount
	if _, err := qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}

func UpdateCustAccountByAppId(m *CustAccount, k ...string) (id int64, err error) {
	o := models.GetDefaultDB()
	v := CustAccount{AppId: m.AppId}
	if err = o.Read(&v, "AppId"); err == nil {
	    m.CustAccountId = v.CustAccountId
		if _, err = o.Update(m, k...); err != nil {
		   id = 0
		   return
		}
		id = m.CustAccountId
	}
	return
}

func DeleteCustAccountByAppid(appId string) (err error) {
	o := models.GetDefaultDB()
	v := CustAccount{AppId: appId}
	if err = o.Read(&v, "AppId"); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}
	
// 使用授权码换取授权信息的返回
func SaveCustTokenByAppId(appId,accessToken,refreshToken string,expiresIn,partnerId,storeId int64) (id int64, err error) {
	o := models.GetDefaultDB()
	v := CustAccount{AppId:appId}
	m := CustAccount{PartnerId:partnerId,StoreId:storeId,AppId:appId,AccessToken:accessToken,ExpiresIn:expiresIn,RefreshToken:refreshToken}
	if err = o.Read(&v, "AppId"); err != nil {
		id, err = o.Insert(&m)
		return
	}
	m.CustAccountId = v.CustAccountId
    if _, err = o.Update(&m,"PartnerId","StoreId","AccessToken","ExpiresIn","RefreshToken"); err != nil {
		id = 0
		return
	}
	id = v.CustAccountId
	return
}

func QueryCustTokenByTime(refTime int64) (custs []*CustAccount, err error) {
	custs = []*CustAccount{}
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(CustAccount)).Filter("expires_in__lte", refTime)
	_, err = qs.All(&custs)
	return
}


func AuthorizerInfoCustAccount(info *oauth.GetAuthorizerInfoResponse) (*CustAccount, error) {
	custAccount := new(CustAccount)
	custAccount.AppId = info.AuthorizationInfo.AuthorizerAppid
	custAccount.NickName = info.AuthorizerInfo.NickName
	custAccount.AvartarUrl = info.AuthorizerInfo.HeadImg
	if info.AuthorizerInfo.MiniProgramInfo != nil {
	    custAccount.ServiceTypeId = 2   //小程序
	}else{
	    custAccount.ServiceTypeId = 1   //公众号
	}
	custAccount.VerifyTypeId = info.AuthorizerInfo.VerifyTypeInfo.Id
    custAccount.PrincipalName = info.AuthorizerInfo.PrincipalName
	custAccount.Alias = info.AuthorizerInfo.Alias
	custAccount.OpenStore = info.AuthorizerInfo.BusinessInfo.OpenStore   
	custAccount.OpenScan = info.AuthorizerInfo.BusinessInfo.OpenScan
	custAccount.OpenPay = info.AuthorizerInfo.BusinessInfo.OpenPay
	custAccount.OpenCard = info.AuthorizerInfo.BusinessInfo.OpenCard
	custAccount.OpenShake = info.AuthorizerInfo.BusinessInfo.OpenShake
	custAccount.QrcodeUrl = info.AuthorizerInfo.QrcodeUrl
	custAccount.Status = 1
	FuncIdArr :=[]string{}
	for _, item := range info.AuthorizationInfo.FuncInfo {
		idStr := strconv.FormatInt(item.FuncScope.Id, 10)
		FuncIdArr = append(FuncIdArr, idStr) 	
	}
	custAccount.FuncIds = strings.Join(FuncIdArr, ",")	
	return custAccount, nil
}
